package com.jiyiren.bms.aty;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.BatteryManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.content.ContextCompat;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.Toolbar;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationListener;
import com.jiyiren.bms.MyConfig;
import com.jiyiren.bms.R;
import com.jiyiren.bms.bean.BatterInfoModel;
import com.jiyiren.bms.bean.BatteryInfo;
import com.jiyiren.bms.net.PostBatteryInfo;
import com.jiyiren.bms.utiltool.MyLog;
import com.jiyiren.bms.utiltool.MyUtils;
import com.jiyiren.bms.utiltool.ShowToast;
import com.zcw.togglebutton.ToggleButton;

public class AtyBattery extends BaseCompatActivity implements SwipeRefreshLayout.OnRefreshListener{

//    App mapp;
    //Model
    BatterInfoModel batterInfoModel;//最终计算存储模型
    BatteryInfo mBatterInfo;        //原生数据存储模型
    private double longitude = 0.0, latitude = 0.0;
    private String userid="0";
    private String resultmsg="";

    //View
    private TextView tv_type, tv_capacity, tv_remain, tv_voltage, tv_temperature, tv_health, tv_longitude,
    tv_latitude;
    private ImageView bt_submit,bt_map;
    private TextView tv_battery_tec,tv_phone_model,tv_phone_manufac,
            tv_ischarging,tv_remain_percent;
    private SwipeRefreshLayout swipeRefreshLayout;
    private ToggleButton toggleButton;

    //高德地图:声明AMapLocationClient类对象
    public AMapLocationClient mLocationClient = null;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_aty_battery);
        initToolBar();
//        mapp=App.getAppInstance();
        registerReceiver(mReceiver, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
        batterInfoModel = new BatterInfoModel();
        mBatterInfo = new BatteryInfo();
        initView();

        initLocation();
    }

    public void initToolBar() {
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);

        toolbar.setNavigationIcon(R.mipmap.logo72);//设置导航栏图标
        toolbar.setNavigationContentDescription(R.string.menu_battery_ico_desc);
//        toolbar.setLogo(R.mipmap.ic_launcher);//设置app logo
        toolbar.setTitle(R.string.menu_battery_title);//设置主标题
        toolbar.setTitleTextColor(ContextCompat.getColor(this, R.color.white));
//        toolbar.setSubtitle("Subtitle");//设置子标题
        toolbar.inflateMenu(R.menu.battery_toolbar_menu);
        toolbar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(MenuItem item) {
                if(item.getItemId()==R.id.action_switch_lang){
                    switchLangDialog(AtyBattery.this);
                }
                return true;
            }
        });
    }

    private void switchLangDialog(Context context){
        String[] items=new String[]{getString(R.string.chinese),getString(R.string.english)};
        AlertDialog.Builder builder=new AlertDialog.Builder(context)
                .setTitle(R.string.menu_switch_lag)
                .setItems(items, new DialogInterface.OnClickListener() {//设置listitem从相册和拍照

                    @Override
                    public void onClick(DialogInterface arg0, int arg1) {
                        // TODO Auto-generated method stub
                        switch (arg1) {
                            case 0:
                                switchLang("zh");
                                break;
                            case 1:
                                switchLang("en");
                                break;
                            default:
                                break;
                        }
                    }
                })
                .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {//取消按钮，并设置点击事件
                    @Override
                    public void onClick(DialogInterface arg0, int arg1) {
                        // TODO Auto-generated method stub
                        arg0.dismiss();//将对话框取消
                    }
                });
        builder.create();
        builder.show();
    }

    public void switchLang(String lang){
        if(!mapp.getLanguage().equals(lang)){
            switchLanguage(lang);
            finish();
            Intent it = new Intent(AtyBattery.this, AtyBattery.class);
            startActivity(it);
        }
    }

    public void initLocation(){
        //初始化定位
        mLocationClient = new AMapLocationClient(getApplicationContext());
        //设置定位回调监听
        mLocationClient.setLocationListener(mAMapLocationListener);
        //启动定位
        mLocationClient.startLocation();
    }

    //位置监听器
    AMapLocationListener mAMapLocationListener=new AMapLocationListener() {
        @Override
        public void onLocationChanged(AMapLocation amapLocation) {
            if (amapLocation != null) {
                if (amapLocation.getErrorCode() == 0) {
                    //解析定位结果
                    longitude=amapLocation.getLongitude();
                    latitude=amapLocation.getLatitude();
                    MyLog.i("jiyiren","Lat:"+amapLocation.getLatitude());
                    MyLog.i("jiyiren","Lat:"+amapLocation.getLongitude());
                }
            }
        }
    };

    //界面初始化
    private void initView() {
        mBatterInfo.setCapacity(getBatteryCapacity());

        swipeRefreshLayout= (SwipeRefreshLayout) findViewById(R.id.swiperefresh_ly);
        swipeRefreshLayout.setColorSchemeResources(android.R.color.holo_blue_light,
                android.R.color.holo_red_light, android.R.color.holo_orange_light,
                android.R.color.holo_green_light);
        swipeRefreshLayout.setOnRefreshListener(this);
        toggleButton= (ToggleButton) findViewById(R.id.bt_toggle);
        if(mapp.getToggled()){
            toggleButton.toggleOn();
        }else{
            toggleButton.toggleOff();
        }

        toggleButton.setOnToggleChanged(new ToggleButton.OnToggleChanged() {
            @Override
            public void onToggle(boolean on) {
                mapp.setToggled(on);
                showLatLng();
            }
        });

        tv_phone_model= (TextView) findViewById(R.id.phone_model);
        tv_phone_manufac= (TextView) findViewById(R.id.phone_manufac);
        tv_battery_tec= (TextView) findViewById(R.id.battery_tec);
        tv_ischarging= (TextView) findViewById(R.id.tv_ischarging);
        tv_remain_percent= (TextView) findViewById(R.id.tv_remain_percent);

        tv_type = (TextView) findViewById(R.id.tv_type);
        tv_capacity = (TextView) findViewById(R.id.tv_capacity);
        tv_remain = (TextView) findViewById(R.id.tv_remain);
        tv_voltage = (TextView) findViewById(R.id.tv_voltage);
        tv_temperature = (TextView) findViewById(R.id.tv_temperature);
        tv_health = (TextView) findViewById(R.id.tv_health);
        tv_longitude = (TextView) findViewById(R.id.tv_longitude);
        tv_latitude = (TextView) findViewById(R.id.tv_latitude);
        bt_submit = (ImageView) findViewById(R.id.bt_update);
        bt_map= (ImageView) findViewById(R.id.bt_map);
        bt_map.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                MapActivity.enterMapAty(AtyBattery.this);
            }
        });
        bt_submit.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                if(mapp.getToggled()){
                    userid=mapp.getSimuUserId();
                }else{
                    userid=mapp.getUserId();
                }
                new PostBatteryInfo(userid, batterInfoModel.getType()+"", batterInfoModel.getCapacity()+"",
                        batterInfoModel.getRemain()+"", batterInfoModel.getVoltage()+"", batterInfoModel.getTemperature()+"",
                        batterInfoModel.getLongtitude()+"", batterInfoModel.getLatitude()+"", batterInfoModel.getHealth()+"",
                        new PostBatteryInfo.SuccessPostBatteryCallback() {
                            @Override
                            public void onSuccess(String result) {
                                String res= MyUtils.getGson(result, MyConfig.KEY_STATE);
                                resultmsg=MyUtils.getGson(result,MyConfig.KEY_MSG);
                                if(res.equals(MyConfig.RESULT_SUCCESS_INSERT)){
                                    userid=MyUtils.getGson(result,MyConfig.KEY_ID);
                                    mHandler.sendEmptyMessage(2);
                                }else{
                                    mHandler.sendEmptyMessage(3);
                                }

                            }
                        }, new PostBatteryInfo.FailPostBatteryCallback() {
                    @Override
                    public void onFail() {
                        ShowToast.show(AtyBattery.this,R.string.check_the_internet);
                    }
                });
            }
        });
    }

    //提供外部进入该activity的方法
    public static void enterBatteryAty(Context context) {
        Intent i = new Intent(context, AtyBattery.class);
        context.startActivity(i);
    }

    //显示所有电池信息
    public void showBatteryInfo() {
        batterInfoModel.setType(1);
        batterInfoModel.setCapacity(mBatterInfo.getCapacity());
        batterInfoModel.setRemain((mBatterInfo.getCapacity() * mBatterInfo.getLevel()) / mBatterInfo.getScale());
        batterInfoModel.setVoltage(((double) mBatterInfo.getVoltage() / 1000));
        batterInfoModel.setTemperature(mBatterInfo.getTemperature() / 10);
        batterInfoModel.setHealth(mBatterInfo.getHealth());

        tv_type.setText(batterInfoModel.getType() + "");
        tv_capacity.setText(batterInfoModel.getCapacity() + "mAh");
        tv_remain.setText(batterInfoModel.getRemain() + "mAh");
        tv_voltage.setText(batterInfoModel.getVoltage() + "V");
        tv_temperature.setText(batterInfoModel.getTemperature() + "℃");
        tv_health.setText(batterInfoModel.getHealth() + "");

        tv_battery_tec.setText(mBatterInfo.getTechnology());
        tv_phone_manufac.setText(getPhoneManufac());
        tv_phone_model.setText(getPhoneModel());
        tv_ischarging.setText(getIsCharging());
        tv_remain_percent.setText(getRemainPercent());
        showLatLng();
        if(swipeRefreshLayout.isRefreshing()){
            swipeRefreshLayout.setRefreshing(false);
        }
    }

    public void showLatLng(){
        if(mapp.getToggled()){
            if(mapp.getLng().equals("0")||mapp.getLat().equals("0")){
                mapp.setLatlng(longitude+"",latitude+"");
            }
            batterInfoModel.setLongtitude(mapp.getLng());
            batterInfoModel.setLatitude(mapp.getLat());
            tv_longitude.setText(batterInfoModel.getLongtitude());
            tv_latitude.setText(batterInfoModel.getLatitude());
            tv_longitude.setTextColor(ContextCompat.getColor(this,R.color.toggle_on));
            tv_latitude.setTextColor(ContextCompat.getColor(this,R.color.toggle_on));
        }else{
            batterInfoModel.setLongtitude(longitude+"");
            batterInfoModel.setLatitude(latitude+"");
            tv_longitude.setText(batterInfoModel.getLongtitude());
            tv_latitude.setText(batterInfoModel.getLatitude());
            tv_longitude.setTextColor(ContextCompat.getColor(this,R.color.toggle_off));
            tv_latitude.setTextColor(ContextCompat.getColor(this,R.color.toggle_off));
        }
    }

    //消息通知
    Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1:
                    showBatteryInfo();
                    break;
                case 2:
                    if(mapp.getToggled()){
                        mapp.setSimuUserId(userid);
                    }else{
                        mapp.setUserId(userid);
                    }
                    ShowToast.show(AtyBattery.this,"id:"+userid+" msg:"+resultmsg);
                    break;
                case 3:
                    ShowToast.show(AtyBattery.this,"id:"+userid+" msg:"+resultmsg);
                    break;
            }
        }
    };

    //电池获取receiver信息的获取
    BroadcastReceiver mReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            int level = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, 0);//the current battery level
            int scale = intent.getIntExtra(BatteryManager.EXTRA_SCALE, 100);//the maximum battery level
            int curpercent = level / scale * 100;//the current battery percent

            int health = intent.getIntExtra(BatteryManager.EXTRA_HEALTH, -1);//the health state of battery
            int plugged = intent.getIntExtra(BatteryManager.EXTRA_PLUGGED, -1);//plugged devices
            int status = intent.getIntExtra(BatteryManager.EXTRA_STATUS, -1);//the status of battery

            String technology = intent.getExtras().getString(BatteryManager.EXTRA_TECHNOLOGY);//the technology of the current battery:Li-ion
            int voltage = intent.getIntExtra(BatteryManager.EXTRA_VOLTAGE, -1);//voltage of battery :mV = V/1000
            int temperature = intent.getIntExtra(BatteryManager.EXTRA_TEMPERATURE, -1);//temperature of battery:摄氏度/10

            mBatterInfo.setLevel(level);
            mBatterInfo.setScale(scale);
            mBatterInfo.setHealth(health);
            mBatterInfo.setPlugged(plugged);
            mBatterInfo.setStatus(status);
            mBatterInfo.setTechnology(technology);
            mBatterInfo.setVoltage(voltage);
            mBatterInfo.setTemperature(temperature);

            MyLog.i("batteryinfo", "BatteryInfo:" + mBatterInfo.toString());
            MyLog.i("batteryinfo", "BatteryTransInfo:" + mBatterInfo.convertToString());
            mHandler.sendEmptyMessage(1);
        }
    };

    //获取电池容量
    public double getBatteryCapacity() {
        Object mPowerProfile_ = null;

        final String POWER_PROFILE_CLASS = "com.android.internal.os.PowerProfile";

        try {
            mPowerProfile_ = Class.forName(POWER_PROFILE_CLASS)
                    .getConstructor(Context.class).newInstance(this);
        } catch (Exception e) {
            e.printStackTrace();
        }

        try {
            double batteryCapacity = (Double) Class
                    .forName(POWER_PROFILE_CLASS)
                    .getMethod("getAveragePower", java.lang.String.class)
                    .invoke(mPowerProfile_, "battery.capacity");
//            Toast.makeText(this, batteryCapacity + " mah",Toast.LENGTH_LONG).show();
            return batteryCapacity;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return 0;
    }

    //取消电池信息监听和位置信息的监听
    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(mReceiver);
        mLocationClient.onDestroy();
    }

    public String getPhoneModel(){
        if( android.os.Build.MODEL!=null){
            return  android.os.Build.MODEL;
        }else{
            return getResources().getString(R.string.phone_default_model);
        }
    }

    public String getPhoneManufac(){
        if(android.os.Build.MANUFACTURER!=null){
            return android.os.Build.MANUFACTURER;
        }else{
            return getResources().getString(R.string.phone_default_manufac);
        }
    }

    public String getRemainPercent(){
        if(mBatterInfo.getLevel()!=0&&mBatterInfo.getScale()!=0){
            return getStringRes(R.string.remaining)+mBatterInfo.getLevel()*100/mBatterInfo.getScale()+"%";
        }else{
            return getStringRes(R.string.remaining_unknown_energy);
        }
    }

    public String getIsCharging(){
        int status=mBatterInfo.getStatus();
        int plugged=mBatterInfo.getPlugged();
        String result=getStringRes(R.string.nocharging);
        if(status==BatteryManager.BATTERY_STATUS_DISCHARGING
                ||status==BatteryManager.BATTERY_STATUS_NOT_CHARGING){
            return result;
        }
        if(status==BatteryManager.BATTERY_STATUS_CHARGING){
            result=getStringRes(R.string.ischarging);
        }else{
            result=getStringRes(R.string.energy_full);
        }

        if(plugged==BatteryManager.BATTERY_PLUGGED_AC){
            result+=getStringRes(R.string.ac);
        }else if(plugged==BatteryManager.BATTERY_PLUGGED_USB){
            result+=getStringRes(R.string.usb);
        }else{
            result+=getStringRes(R.string.unknown);
        }
        return result;
    }


    @Override
    public void onRefresh() {
        showBatteryInfo();
    }

    @Override
    protected void onResume() {
        super.onResume();
        if(mapp.getToggled()){
            toggleButton.toggleOn();
        }else{
            toggleButton.toggleOff();
        }
    }

    public String getStringRes(int id){
        return AtyBattery.this.getResources().getString(id);
    }
}
